package homework;

import network.tcp.EchoClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TCP_EchoClient {
    private Socket socket;

    public TCP_EchoClient(String severIP,int severPort) throws IOException{
        socket = new Socket(severIP,severPort);
    }

    public void start() throws IOException{
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true){
                //1.从控制台读取用户输入
                System.out.println(">");
                String request = scanner.next();
                //2.构造请求发送给服务器
                writer.println(request);
                //刷新缓冲区
                writer.flush();
                //3.读取服务器的响应
                if (!scannerNet.hasNext()){
                    System.out.println("server disconnect");
                    break;
                }
                String response = scannerNet.next();
                //4.把响应显示到控制台
                System.out.println(response);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TCP_EchoClient tcp_echoClient = new TCP_EchoClient("127.0.0.1",9090);
    }
}
